
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate, isAdmin = false, customerName = getQueryVariable("customerName");
let operationNoList = [];
let salesmanCodeList = [];
let deptOperationList=[];
let deptSalesmanList=[];
function getAllJson(jsons) {
    let tmpitem=[]
    if(isEmpty(customerName)){
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            if (item["code"] === user.code) {
                tmparr["selected"] = true;
            }
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
    }else {
        for (let item of jsons) {
            let tmparr={}
            tmparr["value"]=item["code"];
            tmparr["name"]=item["name"];
            tmparr["selected"]=true;
            if(item["users"]){
                for(let it of item["users"]){
                    item["list"].push(it)
                }
            }
            if(item["list"] && item["list"].length){
                tmparr["children"]=   this.getAllJson(item["list"]);
                tmpitem.push(tmparr)
            }else{
                tmpitem.push(tmparr)
            }

        }
    }

    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,

        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}


lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

//判断当前用户是否为管理员 角色 true:是 false 否
function getIsAdmin() {
    $.ajax({
        url: 'customer/isAdmin',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                isAdmin = da.data;
            }
        }
    });
}

let isMBatch = "否";
//采购标签 判断是否有此角色
let purchaseLabel = getAllRolesByCurr("ExportBusiness_Shipmentdetails_Purchase");
layer.ready(function () {
    //判断当前用户是否为管理员
    getIsAdmin();

    if(user.code === "admin" || user.code === "RKB006" || user.code === "RKB004" || user.code === "RKB003"){
        isMBatch = "是";
    }
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();
    let userTree = [];
    if(treeList && treeList.list){
        userTree = getAllJson(treeList.list);
    }else {
        userTree = getAllJson([{name: user.name, code: user.code}]);
    }
    operationNoList = getxmselect("#operationCode","operationCode", userTree);
    salesmanCodeList = getxmselect("#salesmanCode","salesmanCode", userTree);

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

    //获取所有公司信息
    $.ajax({
        url:"receivePayment/getCompanyInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    //公司名称
                    $('#signingCompanyCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });

    let searchURL = window.location.search;
    searchURL = searchURL.substring(1, searchURL.length);
    let type = searchURL.split("&")[0].split("=")[1];
    let operationCodes = operationNoList.getValue("value").join();
    let salesmanCodes = salesmanCodeList.getValue("value").join();
    if(user.code === "admin"){
        operationCodes = "admin";
        salesmanCodes = "admin";
    }
    let obj = {operationCode : operationCodes, salesmanCode : salesmanCodes};
    if(!isEmpty(type) && type == "statistics"){
        //来源于控制台统计

        //获取当月开始日期
        let time = new Date();
        let month = ("0" + (time.getMonth() + 1)).slice(-2);
        let year = time.getFullYear();
        //获取当月第一天
        let startDay = new Date(year, month, 1);
        let startCurryDay = startDay.getDate();
        startCurryDay = startCurryDay < 10 ? '0' + startCurryDay : startCurryDay;
        let startDate = time.getFullYear() + "-" + (month) + "-" + (startCurryDay);
        //制单日期
        laydate.render({
            elem: '#createDateStart',
            value: startDate,
            isInitValue: true
        });

        //获取当月结束日期
        let endDay = new Date(year, month, 0);
        let endCurryDay = endDay.getDate();
        endCurryDay = endCurryDay < 10 ? '0' + endCurryDay : endCurryDay;
        let endDate = time.getFullYear() + "-" + (month) + "-" + (endCurryDay);
        //制单日期
        laydate.render({
            elem: '#createDateEnd',
            value: endDate,
            isInitValue: true
        });

        obj = {operationCode : user.code, createDateStart : startDate, createDateEnd : endDate, statusList : "1,2,3,4"}
    }
    if(!isEmpty(customerName)){
        let name = decodeURI(customerName);
        $("#billNo").val(name);
        obj = {operationCode : operationCodes, salesmanCode : salesmanCodes, billNo : name};
    }

    initTable(obj);

});


form.render();//表单刷新
function initTable(obj){
    table.render({
        elem: '#shipmentdetailsselect'
        ,where:obj
        ,url:'carryDetail/getListByPage'
        ,toolbar: '#shipmentdetailstoolbar'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'billNo', title:'发票编号',sort:true,width: 220,event: "invoicenumber"}
            ,{field:'customerName', title:'客户名称',sort:true,width: 120}
            ,{field:'time', title:'出运日期',sort:true,width: 120}
            ,{field:'currency', title:'币种',sort:true,width: 120}
            ,{field:'usdRate', title:'汇率',sort:true,width: 120}
            ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
            ,{field:'transitPlaceName', title:'起运地',sort:true,width: 120}
            ,{field:'destinationName', title:'目的地',sort:true,width: 120}
            ,{field:'modeOfTransport', title:'运输方式',sort:true,width: 120}
            ,{field:'paymentMethodName', title:'付款方式',sort:true,width: 120}
            ,{field:'priceTermsName', title:'价格术语',sort:true,width: 120}
            ,{field:'totalInvoiceAmount', title:'发票总额',sort:true,width: 120}
            ,{field:'containerType', title:'货柜型号',sort:true,width: 120}
            ,{field:'numberOfContainers', title:'货柜数量',sort:true,width: 120}
            ,{field:'createDate', title:'制单日期',sort:true,width: 120}
            ,{field:'salesContractNo', title:'销售合同号',sort:true,width: 220}
            ,{field:'customerContractNo', title:'客户合同号',sort:true,width: 220}
            ,{field:'salesmanName', title:'业务员',sort:true,width: 120}
            ,{field:'businessModelName', title:'业务模式',sort:true,width: 120}
            ,{field:'articleNumberDate', title:'货好日期',sort:true,width: 120}
            ,{field:'warehouseName', title:'仓库',sort:true,width: 120}
            ,{field:'accountingPeriod', title:'账期',sort:true,width: 120}
            ,{field:'carryPlanNo', title:'出运计划号',sort:true,width: 220}
            ,{field:'actualTimeDismissal', title:'预计开船日期 ',sort:true,width: 200}
            ,{field:'loadingTime', title:'进仓装柜日期 ',sort:true,width: 180}
            ,{field:'signingCompanyName', title:'签约公司 ',sort:true,width: 120}
            ,{field:'bankName', title:'银行 ',sort:true,width: 120}
            ,{field:'operator', title:'操作员',sort:true,width: 120}
            ,{field:'statusStr', title:'单据类型',sort:true,width: 120}
            ,{fixed: 'right', width:340, toolbar: '#shipmentdetailseditor', title:'操作'}
        ]]
        ,id: 'shipmentdetailstableid'
        ,height: $(document).height() - $('#shipmentdetailsselect').offset().top - 50
        ,page: true
        ,limit: 50
        ,limits: [50, 100, 200, 300, 500]
        ,done:function (res, curr, count) {
            if(purchaseLabel){
                //采购标签:控制"发票总额"
                //发票总额
                $("[data-field='totalInvoiceAmount']").css("display", "none");
            }
        }
    });
}

table.on('tool(shipmentdetailstable)', function(obj){
    let data = obj.data;
    let id = data.id;
    if(obj.event === 'update') {
        //校验数据是否被调用
        $.ajax({
            url: "carryDetail/checkDataIsUsed?shipmentDetailNo=" + data.billNo,
            async: false,
            success: function (res) {
                if (res.status == 200) {
                    if (0 === res.data) {
                        parent.intab("views/jsp/ExportBusiness/tpl/updateCarryDetail.jsp?id=" + obj.data.id, "修改出运明细")
                    } else if (1 === res.data) {
                        layer.msg("已做报关，无法修改", {icon: 5});
                    } else if (2 === res.data) {
                        layer.msg("已做结汇，无法修改", {icon: 5});
                    } else if (3 === res.data) {
                        layer.msg("已做付款，无法修改", {icon: 5});
                    }

                } else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    }else if(obj.event === 'delect'){
        layer.confirm('确认删除？',confirmInfo(3,6), function (index) {
            layer.close(index);
            let dataBases={
                id:id,
                status:data.status
            }
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(dataBases),
                url:"carryDetail/delete",
                success:function(res){
                    if(res.status == 200){
                        layer.msg("删除成功", {icon: 6});
                        table.reload('shipmentdetailstableid', {
                            page: {
                                curr: 1 //重新从第 1 页开始
                            }
                            ,where: data.field
                        }, 'data');
                        return false;
                    }else {
                        layer.msg(res.msg, {icon: 5});
                    }
                }
            });
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', confirmInfo(3, 5), function (index) {
            operationData(data, 1, "提交审批");
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', confirmInfo(3, 5), function (index) {
            operationData(data, 2, "审批通过");
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', confirmInfo(3, 5), function (index) {
            operationData(data, 3, "审批退回");
        });
    }else if(obj.event === 'termination'){
        layer.confirm('确定终止吗', confirmInfo(3, 5), function (index) {
            operationData(data, 6, "终止");
        });
    }else if(obj.event === 'terminationBack'){
        layer.confirm('确定取消终止吗', confirmInfo(3, 5), function (index) {
            operationData(data, 7, "取消终止");
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', confirmInfo(3, 5), function (index) {
            operationData(data, 4, "完成");
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', confirmInfo(3, 5), function (index) {
            operationData(data, 5, "还原");
        });
    }else if (obj.event === "invoicenumber"){
        parent.intab("views/jsp/ExportBusiness/tpl/viewshipmentdetails.jsp?id="+obj.data.id,"出运明细")
    }else if (obj.event === "terminationDetail"){
        parent.intab("views/jsp/ExportBusiness/tpl/carryDetailEnd.jsp?id="+obj.data.id,"出运明细变更")
    }
});

function operationData(dataSource, operation, msg){
    let data = {
        id : dataSource.id,
        operation: operation,
        billNo: dataSource.billNo
    }
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(data),
        url:"carryDetail/operation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('shipmentdetailstableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

form.on('submit(submitform)', function(data){
    initTable(data.field);
    return false;
});

table.on('toolbar(shipmentdetailstable)', function(obj){
    let checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/newupshipmentdetails.jsp","新增出运明细")
            break;
        case 'print':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的单据! ");
                break;
            }
            window.open("views/jsp/report.jsp?ym=rcanReport&code=code:"+checkStatus.data[0].id)
            break;
        case 'checkSubmit':
            batchOperation(checkStatus.data, "一键关账成功！", 1);
            break;
        case 'checkAdopt':
            batchOperation(checkStatus.data, "一键取消成功！", 2);
            break;

    };
});

//一键操作
function batchOperation(data, msg, type){
    if(data.length == 0){
        layer.msg("请选择数据！", {icon: 5});
        return;
    }
    let fields = {};
    fields["type"] = type;
    fields["operationReqs"] = data;
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:JSON.stringify(fields),
        url:"carryDetail/batchOperation",
        success:function(res){
            if(res.status == 200){
                layer.msg(msg, {icon: 6});
                table.reload('shipmentdetailstableid', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: data.field
                }, 'data');
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
}

layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("contractStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/tpl/carryDetailStatistics1.jsp", "按出运明细统计采购应付款")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/tpl/carryDetailStatistics2.jsp", "供应商出货详情统计")
                break
            case "s3":
                parent.intab("views/jsp/ExportBusiness/tpl/carryDetailStatistics3.jsp", "已做明细未结汇")
                break
            case "s4":
                parent.intab("views/jsp/ExportBusiness/tpl/carryDetailShippedUnExchange.jsp", "已出运未结汇（物流）")
                break
        }
    });
})


//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

document.getElementById('clear').onclick = function(){
    operationNoList.setValue([ ]);
    salesmanCodeList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
};